<?php
namespace app\mobile\controller;
use think\Db;
class ActivityController extends WechatController
{

    public function details()
    {
    	$id = input('id/d',0);
    	$this->assign('id',$id);
    	$m_activity = Db::name('activity')->find($id);
    	$user_count =  Db::name('activity_log')->where('act_id',$id)->count('id');
    	$m_activity["user_count"] = $user_count;
    	$this->assign('m_activity',$m_activity);
        return $this->fetch();
    }
    public function signin(){
        return $this->fetch();
    }
    function ajax_act_sign(){
        $result=[];
        $now = time();
        $valid_distance = 100; /*该变量来说明签到距离 100 */
        $act=input('post.act/d',0); /* 1 代表签到，2 签退*/
        $location = input('post.location/a',[]);
        $act_id = input('post.act_id/d',0);

        try{
            if($act <=0){
                throw new \Exception("动作异常", 1);        
            }
            if(empty($location)){
                throw new \Exception("签到地址错误", 1);                
            }
            if($act_id==0){
                throw new \Exception("活动信息异常", 1);          
            }
            $act_info = Db::name('activity')->field('point,start_time,end_time,place')->find($act_id);
            if(!$act_info){
                throw new \Exception("活动信息异常");
            }
            $start_time=$act_info['start_time'];
            $end_time = $act_info['end_time'];
            $find=Db::name('activity_pre_log')->where(['user_id'=>$this->user_id,'act_id'=>$act_id])->select();
            if(count($find)==0){
                throw new \Exception("您未报名该活动，请先报名再参与~",100);
            }
            $loi  = explode(',', $act_info['location']);
            $distance = TX_Map_Api_distance($loi[0],$loi[1], $location['lat'],$location['lng']);
            $place=$act_info['place'];
            if($distance> $valid_distance){
                throw new \Exception("距离过远，签到失败!当前距离活动地点".intval($distance).'米',100);
            }
            $where= ['user_id'=>$this->user_id,'act_id'=>$act_id];
            if($act == 1){
                $count=Db::name('activity_log')->where($where)->where('start_time','>',$start_time-30*60)->where('start_time','<',$end_time+30*60)->count();
                if($count>0){
                    throw new \Exception('您已参与过此时间段的该活动~。',100);
                }
                $res=Db::name('activity_log')->insert([
                    'user_id'=>$this->user_id,
                    'act_id'=>$act_id,
                    'start_time'=>$now,
                    'location'=>$location['lat'].','.$location['lng'],
                    'place' =>  $place /* 此处记录的离着当前位置最近的签到位置信息 */
                ]);
                if($res){
                    $result["errmsg"] = '签到成功!';
                }
            }else{
                if($now<$start_time-30*60){
                    throw new \Exception('此时间段该活动尚未开始，无法签退~。');
                }
                if($now>$end_time+60*30){
                    throw new \Exception('已错过此时间段该活动最晚签退打卡时间~。');
                }

                $data=Db::name('activity_log')->where($where)->where('start_time','>',$start_time-30*60)->where('start_time','<',$end_time+30*60)->find();
                $log_start_time = Db::name('activity_log')->where($where)->value('start_time');
                if($log_start_time==null){
                    throw new \Exception('请先打卡~。',100);
                }
                if($now>$now_interval[1]){
                    if($start_time<$now_interval[0]){
                        $duration = $now_interval[1] - $now_interval[0];
                    }else{
                        $duration = $now_interval[1] - $start_time;
                    }
                }else{
                    if($start_time<$now_interval[0]){
                        $duration = $now - $now_interval[0];
                    }else{
                        $duration = $now - $start_time;
                    }
                }

//                    Db::name('activity_log')->where($where)->update([
//                        'end_time'=>$now,
//                        'duration' => $duration
//                    ]);
//                $result["errmsg"]='签退成功!';
                if($duration>60*15) {
                    Db::name('activity_log')->where($where)->update([
                        'end_time'=>$now,
                        'duration' => $duration
                    ]);
                    $point_rule=Db::name('point_rule')->where('org_id',1)->find();
                    $rule=$point_rule['point']/$point_rule['num'];
                    $minute=$duration/60;
                    $points=$duration/3600*$rule;
                    $user_rank=Db::name('user_rank')->where('user_id',$this->user_id)->find();
                    if($user_rank){
                        if(!empty($data['end_time'])){
                            $result["errmsg"]='更新签退成功~本次累计活动时长'.round($minute).'分钟';
                            $user_rank['duration']=$user_rank['duration']+$duration-$data['duration'];
                            $user_rank['all_points']=$user_rank['all_points']+ $points-$data['duration']/3600*$rule;
                            $user_rank['can_points']=$user_rank['can_points']+ $points-$data['duration']/3600*$rule;
                            Db::name('user_rank')->update($user_rank);
                        }else{
                            $user_rank['duration']=$user_rank['duration']+$duration;
                            $user_rank['q_times']=$user_rank['q_times']+1;
                            $user_rank['all_points']=$user_rank['all_points']+ $points;
                            $user_rank['can_points']=$user_rank['can_points']+ $points;
                            Db::name('user_rank')->update($user_rank);
                            $result["errmsg"]='签退成功!本次累计活动时长'.round($minute).'分钟';
                        }

                    }else{
                        Db::name('user_rank')->insert(['user_id'=>$this->user_id,'duration'=>$duration,'q_times'=>1,'all_points'=>$points,'can_points'=>$points]);
                    }
                }else{
                    Db::name('activity_log')->where($where)->update([
                        'end_time'=>$now,
                    ]);
                    $result["errmsg"]='签退成功!未满15分钟不计算时长和积分~记得更新打卡哦';
                }
            }
            
            $result['data']=$location;
            $result['error']=false;
        }catch(\Exception $e){

            $result["error"]= true;
            $msg= "[{$e->getLine()}]".$e->getMessage();
            if($e->getCode()==100){
                $msg= $e->getMessage();
            }
            $result['errmsg']=$msg;
        }
        return json($result);
    }

    function ajax_get_current_activity(){
        $result=[];
        $now = time();
        try{
            $sql = "SELECT l.act_id, a.title, a.point,a.place,a.start_time,a.end_time,a.time FROM cmf_activity_pre_log l INNER JOIN cmf_activity a ON l.act_id = a.id WHERE (l.user_id = {$this->user_id} AND a.start_time <= $now AND a.end_time >= $now)";
            $activity_info = Db::query($sql);
            if(count($activity_info)==0){
                throw new \Exception("未找到您当前报名的活动", 1);
            }
            $result['data']=$activity_info;
            $result["errmsg"] = 'SUCCESS';
            $result['error']=false;
        }catch(\Exception $e){
            $result["error"]= true;
            $result['errmsg']="[{$e->getLine()}]".$e->getMessage();
        }
        return json($result);
    }
    public function index(){
        return $this->fetch();
    }
    public function ajax_join(){
        $result= [];
        $act_id = input("id/d",0);
        try{
            if($act_id<=0){
                throw new \Exception('活动信息异常，请稍后再试。');
            }
            $start_time=Db::name('activity')->where('id',$act_id)->value('start_date');
            $end_time=Db::name('activity')->where('id',$act_id)->value('end_date');
            if(time()<$start_time-60*30||time()>$end_time+60*30){
                throw new \Exception('不在活动打卡时间内~。');
            }
            $result["error"] = false;
            $result["errmsg"] = "正在跳转活动签到页面~";

        }catch(\Exception $e){
            $result["error"] = true;
            $result["errmsg"] = $e->getMessage();
        }
        return json($result);
    }
    //活动预报名
    public function pre_join(){
        $result= [];
        $act_id = input("id/d",0);
        try{
            if($act_id<=0){
                throw new \Exception('活动信息异常，请稍后再试。');
            }
            $activity=Db::name('activity')->where('id',$act_id)->field('start_time,end_time,org_id,max_people')->find();
            $status=Db::name('user_organize')->where(['user_id'=>$this->user_id])->value('status');
            if($status!=1){
                throw new \Exception('加入志愿者并通过审核才能参加活动~');
            }
            if($activity['end_date']<time()){
                throw new \Exception('该活动已经结束~');
            }
            $max=$activity['max_people'];
            $count =  Db::name('activity_pre_log')->where([
                'act_id'=>$act_id
            ])->count();
            if($count>=$max&&$max!=0){
                throw new \Exception('此活动报名人数已达上限~。');
            }
            $count =  Db::name('activity_pre_log')->where([
                'user_id'=>$this->user_id,
                'act_id'=>$act_id
            ])->count('id');
            if($count>0){
                throw new \Exception('您已报名此活动~。');
            }
            $info = [
                'user_id'=>$this->user_id,
                'act_id'=>$act_id,
                'ctime'=>time()
            ];
            $log_id = Db::name('activity_pre_log')->insertGetID($info);
            if(!$log_id){
                throw new \Exception('报名失败，请稍后再试');
            }
            $result["error"] = false;
            $result["errmsg"] = "您已成功报名此次活动";

        }catch(\Exception $e){
            $result["error"] = true;
            $result["errmsg"] = $e->getMessage();
        }
        return json($result);
    }
    public function test(){
        $point_rule=Db::name('point_rule')->where('org_id',1)->find();
        $rule=$point_rule['point']/$point_rule['num'];
        dump($rule);
        dump($point_rule);
    }
}